package sicnu.cs.ich.security.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import sicnu.cs.ich.common.util.SpringUtils;
import sicnu.cs.ich.security.security.token.AccessToken;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/12/26-14:10
 **/
@Slf4j
public class WxUtils {
    public final static String CODE_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?";
    public final static String CODE_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session?";
    public final static String APPID = "wxf0893441501b0ceb";
    public final static String APPSecret = "2a6cfcb4d069bab0ca80ea325a60ccad";
    //    public final static String APPID = "wxf0893441501b0ceb";
//    public final static String APPSecret = "8387ada29dede236a7a9705208939c4d";
    public final static String PARAM_APPID = "appid";
    public final static String PARAM_SECRET = "secret";
    public final static String PARAM_GRANT_TYPE = "grant_type";
    public final static String PARAM_CODE = "js_code";
    public final static String GRANT_TYPE = "authorization_code";

    public static AccessToken getCodeAccessToken(String code) {
        AccessToken accessToken = null;
        HashMap<String, String> params = new HashMap<String, String>();
        params.put(PARAM_APPID, APPID);
        params.put(PARAM_SECRET, APPSecret);
        params.put(PARAM_GRANT_TYPE, GRANT_TYPE);
        Map<String, Object> resultMap = getWxAPI(CODE_ACCESS_TOKEN_URL, params);
        accessToken = AccessToken.builder()
                .openid((String) resultMap.get("openid"))
                .token((String) resultMap.get("access_token"))
                .build();
        //accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
        return accessToken;
    }

    public static Map<String, Object> getWxAPI(String url, Map<String, String> params) {
        //拼接url
        StringBuilder wxUrl = new StringBuilder(url);
        params.forEach((key, value) -> {
            wxUrl.append(key).append("=");
            wxUrl.append(value).append("&");
        });
        url = wxUrl.substring(0, wxUrl.length() - 1);
        log.info("请求路径" + url);
        Map<String, Object> map = null;
        try {
            RestTemplate restTemplate = (RestTemplate) SpringUtils.getBean("restTemplate");
//            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
//            HttpGet get = new HttpGet(url.toString());    //构建一个GET请求
//            HttpResponse response = client.execute(get);//提交GET请求
//            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
            String content = result.getBody();
            log.info("微信返回实体：" + content);
            JSONObject res = JSONObject.parseObject(content);
            map = res.getInnerMap();
            //把信息封装到map
//            map = (Map<String, Object>) JSON.parse(content);
            log.info("map:" + map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("请求微信接口失败");
        }
        return map;
    }

    public static Map<String, Object> wechatLoginByCode(String wechatCode) {
        log.info("获取到微信code" + wechatCode);
        //待用
        Map<String, String> params = new HashMap<>();
        params.put(PARAM_CODE, wechatCode);
        params.put(PARAM_APPID, APPID);
        params.put(PARAM_SECRET, APPSecret);
        params.put(PARAM_GRANT_TYPE, GRANT_TYPE);
        Map<String, Object> result = getWxAPI(CODE_OPENID_URL, params);
        log.info("请求微信接口获取到的参数" + result);
        return result;
    }
}
